package com.sitanyun.merchant.guide.frament.view.activity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.sitanyun.merchant.guide.R;
import com.sitanyun.merchant.guide.base.BaseActivity;
import com.sitanyun.merchant.guide.url.Urls;
import com.sitanyun.merchant.guide.weiht.DateUtils;
import com.sitanyun.merchant.guide.weiht.SharedPreferenceUtil;
import com.sitanyun.merchant.guide.weiht.WxShareUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import androidx.core.app.ActivityCompat;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 注册海报
 */
public class RegiPosterActivity extends BaseActivity {

    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.tv_nodename)
    TextView tvNodename;
    @BindView(R.id.tv_zy)
    TextView tvZy;
    @BindView(R.id.im_wx)
    ImageView imWx;
    @BindView(R.id.tv_save)
    TextView tvSave;
    @BindView(R.id.tv_wx)
    TextView tvWx;
    @BindView(R.id.tv_pyq)
    TextView tvPyq;
    @BindView(R.id.ll_layout)
    LinearLayout layout_poster;
    private String urls;
    private Bitmap mBitmap;
    private int width = 280;
    private int height = 280;
    private int type;
    private static final int REQUEST_STATE_CODE = 1010;
    @Override
    public int getLayoutId() {
        return R.layout.activity_regi_poster;
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        setFindViewById(true);
        setTitleStr("注册海报");
        String storename = getIntent().getStringExtra("zy");
        if (storename.equals("1")) {
            urls = Urls.urls + "/mer/mobile-register/?role=51&inviterId="+SharedPreferenceUtil.getStringData("staffid")+"&nodeId="+SharedPreferenceUtil.getStringData("tonodeid")+"#/MainPage";
            tvZy.setText("店长");
        } else {
            urls = Urls.urls + "/mer/mobile-register/?role=52&inviterId="+SharedPreferenceUtil.getStringData("staffid")+"&nodeId="+SharedPreferenceUtil.getStringData("tonodeid")+"#/MainPage";
            tvZy.setText("导购");
        }
        tvName.setText(SharedPreferenceUtil.getStringData("staffname") + "邀请您加入");
        tvNodename.setText(SharedPreferenceUtil.getStringData("tonodename"));
        zxing(urls);
    }

    //生成二维码
    private void zxing(String urls) {
        QRCodeWriter qrCodeWriter = new QRCodeWriter();
        Map<EncodeHintType, String> hints = new HashMap<>();
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8"); //记得要自定义长宽
        BitMatrix encode = null;
        try {
            encode = qrCodeWriter.encode(urls, BarcodeFormat.QR_CODE, width, height, hints);
        } catch (WriterException e) {
            e.printStackTrace();
        }
        int[] colors = new int[width * height];
        //利用for循环将要表示的信息写出来
        for (int i = 0; i < width; i++) {
            for (int j = 0; j < height; j++) {
                if (encode.get(i, j)) {
                    colors[i * width + j] = Color.BLACK;
                } else {
                    colors[i * width + j] = Color.WHITE;
                }
            }
        }

        Bitmap bit = Bitmap.createBitmap(colors, width, height, Bitmap.Config.RGB_565);
        imWx.setImageBitmap(bit);
    }

    @Override
    public void initView() {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @OnClick({R.id.tv_save, R.id.tv_wx})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_save:
                if (DateUtils.isFastClick()) {
                    return;
                }
                // 保存海报图片
                type = 1;
                savePoster();
                break;
            case R.id.tv_wx:
                if (DateUtils.isFastClick()) {
                    return ;
                }
                type = 2;
                if (mBitmap == null) {
                    savePoster();
                    WxShareUtils.shareImage(0, RegiPosterActivity.this,
                            "wx7cb638590873ca35", mBitmap);
                } else {
                    WxShareUtils.shareImage(0, RegiPosterActivity.this,
                            "wx7cb638590873ca35", mBitmap);
                }
                break;
        }
    }

    private void savePoster() {
        // 1.View截图
        layout_poster.setDrawingCacheEnabled(true);
        // 重新测量View
        layout_poster.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
                View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
        // 2.创建一个Bitmap
        mBitmap = layout_poster.getDrawingCache();
        // 3.保存到SD卡
        if (mBitmap != null) {
            //判断是否为Android 6.0 以上的系统版本，如果是，需要动态添加权限
            if (Build.VERSION.SDK_INT >= 23) {
                requestPermissionss();
            } else {
                saveToLocal(mBitmap);
            }
        }

    }

    //动态权限
    private void requestPermissionss() {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            // 申请一个（或多个）权限，并提供用于回调返回的获取码（用户定义）
            ActivityCompat.requestPermissions(this, new String[]{
                    Manifest.permission.WRITE_EXTERNAL_STORAGE
            }, REQUEST_STATE_CODE);
        } else {
            saveToLocal(mBitmap);
        }
    }

    /**
     * 保存一张Bitmap图到本地
     */
    private void saveToLocal(Bitmap bitmap) {
        try {
            File appDir = new File(Environment.getExternalStorageDirectory(), "Poster");
            // 没有目录创建目录
            if (!appDir.exists()) {
                appDir.mkdir();
            }
            File file = new File(appDir, "view_" + System.currentTimeMillis() + ".jpg");
            FileOutputStream out;
            try {
                out = new FileOutputStream(file);
//                bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
                if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, out)) {
                    out.flush();
                    out.close();
                    // 通知图库更新
                    Uri uri = Uri.fromFile(file);
                    Intent scannerIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri);
                    sendBroadcast(scannerIntent);
                    if (type == 1) {
                        Toast.makeText(this, "保存图片到相册成功", Toast.LENGTH_SHORT).show();
                    }

                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case REQUEST_STATE_CODE:
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    saveToLocal(mBitmap);
                } else {
                    Toast.makeText(this, "没有开启存储权限，保存失败!", Toast.LENGTH_LONG).show();
                    return;
                }
                break;
            default:
                break;
        }
    }
}
